/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.liycloud.auth.service;

// pigx
import com.liycloud.sys.api.dto.UserInfo;
import com.liycloud.sys.api.entity.SysUser;
import com.liycloud.sys.api.feign.RemoteUserServiceFeign;

import com.liycloud.common.core.constant.CacheConstants;
import com.liycloud.common.core.constant.CommonConstants;
import com.liycloud.common.core.constant.SecurityConstants;
import com.liycloud.common.core.util.ResultVo;
import com.liycloud.common.security.service.PigxUser;
import com.liycloud.common.security.service.PigxUserDetailsService;

import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

// spring
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

// hutool
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * 用户详细信息服务实现类
 *
 * @author lengleng
 */
@Slf4j
@Service
@AllArgsConstructor
public class PigxUserDetailsServiceImpl implements PigxUserDetailsService {

	// 远程用户信息服务接口
	private final RemoteUserServiceFeign remoteUserService;

	// 缓存管理器
	private final CacheManager cacheManager;

	/**
	 * 用户密码登录
	 * @param username 用户名
	 * @return
	 * @throws UsernameNotFoundException
	 */
	@Override
	@SneakyThrows
	public UserDetails loadUserByUsername(String username) {

		// 缓存管理器  指定的 varName
		Cache cache = cacheManager.getCache(CacheConstants.USER_DETAILS);

		if(cache != null){
			Cache.ValueWrapper valueWrapper = cache.get(username);
			if (valueWrapper != null) {
				Object value = valueWrapper.get();
				return (PigxUser) value;
			}
		}

		// 缓存没有就从远程服务中获取用户信息
		ResultVo<UserInfo> result = remoteUserService.info(username, SecurityConstants.FROM_IN);

		UserDetails userDetails = getUserDetails(result);

		//
		cache.put(username, userDetails);

		return userDetails;
	}


	/**
	 * 根据社交登录 code 登录, 包括手机验证码
	 * @param inStr TYPE@CODE
	 * @return UserDetails
	 * @throws UsernameNotFoundException
	 */
	@Override
	@SneakyThrows
	public UserDetails loadUserBySocial(String inStr) {
		return getUserDetails(remoteUserService.social(inStr, SecurityConstants.FROM_IN));
	}


	/**
	 * 构建 user_details
	 * @param result 用户信息
	 * @return
	 */
	private UserDetails getUserDetails(ResultVo<UserInfo> result) {

		if (result == null || result.getData() == null) {
			throw new UsernameNotFoundException("用户不存在");
		}

		UserInfo info = result.getData();
		Set<String> dbAuthsSet = new HashSet<>();
		if (ArrayUtil.isNotEmpty(info.getRoles())) {
			// 获取角色
			Arrays.stream(info.getRoles()).forEach(roleId -> dbAuthsSet.add(SecurityConstants.ROLE + roleId));
			// 获取资源
			dbAuthsSet.addAll(Arrays.asList(info.getPermissions()));

		}
		Collection<? extends GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(dbAuthsSet.toArray(new String[0]));
		SysUser user = info.getSysUser();
		boolean enabled = StrUtil.equals(user.getLockFlag(), CommonConstants.STATUS_NORMAL);
		// 构造security用户

		return new PigxUser(user.getUserId(), user.getDeptId(), user.getPhone(), user.getAvatar(), user.getTenantId(),
				user.getUsername(), SecurityConstants.BCRYPT + user.getPassword(), enabled, true, true,
				!CommonConstants.STATUS_LOCK.equals(user.getLockFlag()), authorities);
	}

}
